package com.framework.loippi.controller.doctor;

import com.framework.loippi.cache.ConfigCache;
import com.framework.loippi.controller.GenericController;
import com.framework.loippi.controller.t_user.TLSSigAPIv2;
import com.framework.loippi.entity.Doctor;
import com.framework.loippi.entity.ImUser;
import com.framework.loippi.entity.User;
import com.framework.loippi.service.DepartmentService;
import com.framework.loippi.service.DoctorService;
import com.framework.loippi.service.ImUserService;
import com.framework.loippi.service.UserService;
import com.framework.loippi.support.Message;
import com.framework.loippi.support.Pageable;
import com.framework.loippi.utils.ParameterUtils;
import com.framework.loippi.utils.RandomUtils;
import com.framework.loippi.utils.StringUtil;
import com.qcloud.cos.utils.StringUtils;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller - 医生表
 *
 * @author wmj
 * @version 2.0
 */
@Controller("adminDoctorController")
@RequestMapping({"/admin/doctor"})
public class DoctorController extends GenericController {

    @Resource
    private DepartmentService departmentService;
    @Resource
    private DoctorService doctorService;
    @Resource
    private ImUserService imUserService;
    @Resource
    private UserService userService;

    /**
     * 跳转添加页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = {"/add"}, method = {RequestMethod.GET})
    public String add(ModelMap model) {
        model.addAttribute("departments", departmentService.findAll());
        return "/admin/doctor/add";
    }

    /**
     * 删除操作
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST})
    public @ResponseBody
    Message delete(Long[] ids) {
        this.doctorService.deleteAll(ids);
        return SUCCESS_MESSAGE;
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable Long id, ModelMap model) {
        Doctor doctor = doctorService.find(id);
        model.addAttribute("departments", departmentService.findAll());
        model.addAttribute("doctor", doctor);
        return "/admin/doctor/edit";
    }

    /**
     * 查询所有医生
     *
     * @return
     */
    @RequestMapping(value = {"/findAll"}, method = {RequestMethod.GET})
    public List<Doctor> findAll() {
        List<Doctor> list = doctorService.findAll();
        return doctorService.findAll();
    }

    /**
     * 列表查询
     *
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = {"/list"}, method = {RequestMethod.GET})
    public String list(Pageable pageable, HttpServletRequest request, ModelMap model) {

        Map<String, Object> paramter = ParameterUtils.getParametersMapStartingWith(request, "filter_");
        Map map = new HashMap();
        for (String key : paramter.keySet()) {
            if (!StringUtil.isEmpty(paramter.get(key).toString())) {
                map.put(key, paramter.get(key));
            }
        }
        String keyword = request.getParameter("keyword");
        if (!StringUtils.isNullOrEmpty(keyword)) {
            map.put("nameLike", keyword);
            map.put("phoneLike", keyword);
            map.put("departLike", keyword);
        }
        pageable.setParameter(map);
        model.addAttribute("paramter", paramter);
        model.addAttribute("page", this.doctorService.findByPage(pageable));
        return "/admin/doctor/list";
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String save(Doctor doctor, RedirectAttributes redirectAttributes) {
        Doctor phoneDoctor = doctorService.findByPhone(doctor.getPhone());
        if (phoneDoctor == null) {
            // 将医生添加为后台操作人员
            User user = new User();
            String password = doctor.getPhone().substring(5, 11);
            user.setUsername(doctor.getPhone());
            user.setNickname(doctor.getName());
            user.setRoleId(2L);
            user.setPassword(DigestUtils.md5Hex(password));
            user.setIsLocked(false);
            user.setLoginFailureCount(0);
            user.setIsEnabled(Boolean.TRUE);
            user.setLockedDate(null);
            user.setLoginDate(null);
            user.setLoginIp(null);
            user.setCreateDate(new Date());
            userService.save(user);

            ImUser doctorImUser = new ImUser();
            doctorImUser.setAvatar(doctor.getAvatarUrl());
            doctorImUser.setNickName(doctor.getName());
            doctorImUser.setCreateTime(new Date());
            imUserService.save(doctorImUser);
            doctor.setImUserId(doctorImUser.getId());
            doctorService.save(doctor);
//		将医生注册到腾讯im
            MediaType mediaType = MediaType.get("application/json; charset=utf-8");
            OkHttpClient client = new OkHttpClient();
//      构造腾讯im导入用户资料参数
            String key = ConfigCache.getConfig("tx.im.key");
            Long sdkappid = Long.valueOf(ConfigCache.getConfig("tx.im.sdkappid"));
            String identifier = ConfigCache.getConfig("tx.im.identifier");
            String random = RandomUtils.getRandomNumberString(9);
            long expire = 180 * 24 * 3600;
            TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(sdkappid, key);
            String userSign = tlsSigAPIv2
                    .genSig(doctorImUser.getId().toString(), expire);
            doctorImUser.setUserSign(userSign);
            imUserService.update(doctorImUser);
            JSONObject json = new JSONObject();
            json.put("Identifier", doctorImUser.getId());//用户名
            json.put("Nick", doctor.getName());//昵称
            json.put("FaceUrl", doctor.getAvatarUrl());//头像
            RequestBody body = RequestBody.create(String.valueOf(json), mediaType);
            Request request = new Request.Builder()
                    .url("https://console.tim.qq.com/v4/im_open_login_svc/account_import" +
                            "?sdkappid=" + sdkappid
                            + "&identifier=" + identifier
                            + "&usersig=" + userSign
                            + "&random=" + random
                            + "&contenttype=json")
                    .post(body)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                System.out.println(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            addFlashMessage(redirectAttributes, Message.error("该号码已存在"));
        }

        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String update(Doctor doctor, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        doctorService.update(doctor);
        //对应的修改医生角色的username,nickname,password
        Map<String, Object> paramter = ParameterUtils.getParametersMapStartingWith(request, "filter_");
        Map map = new HashMap();
        for (String key : paramter.keySet()) {
            if (!StringUtil.isEmpty(paramter.get(key).toString())) {
                map.put(key, paramter.get(key));
            }
        }
        String phoneOld = request.getParameter("phoneOld");
        List<User> userList = userService.findByUserName(phoneOld);
        if (userList != null && !userList.isEmpty()) {
            User user = userList.get(0);
            user.setUsername(doctor.getPhone());
            user.setNickname(doctor.getName());
            user.setPassword(DigestUtils.md5Hex(doctor.getPhone().substring(5, 11)));
            userService.update(user);
        }
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public String view(@PathVariable Long id, ModelMap model) {
        Doctor doctor = doctorService.find(id);
        model.addAttribute("doctor", doctor);
        return "/admin/doctor/view";
    }
}
